<?php

namespace App\Http\Services;


use App\Http\Model\Hint;
use App\Http\Model\UserCoolval;
use App\Http\Model\User;
use App\Modules\Relationship\Models\QueueExecModel;
use Illuminate\Support\Facades\DB;

/**
 * 用户炫酷值
 * Class UserCoolvalServices
 * @package App\Http\Services
 */
class UserCoolvalServices extends CommonServices
{

    protected $modelCoolval;

    public function __construct()
    {
        parent::__construct();
        $this->modelCoolval = new UserCoolval();
    }

    /**
     * 炫酷等级列表
     */
    public function getCoolLevel($level=0):array
    {
        $levelList = [];
        $list = $this->modelCoolval -> getCoolLevel();
        if ($list){
            $levelList = array_map(function ($val){
                $val['icon_url'] = build_image($val['icon']);
                $val['icon_grey_url'] = build_image($val['icon_grey']);
                return $val;
            }, $list);
        }

        if ($level){
            $list = array_column($levelList, NULL, 'level');
            if ($list && isset($list[$level]) ){
                $levelList = $list[$level];
            }
        }

        return (array)$levelList;
    }

    /**
     * 炫酷等级列表
     * @return array
     */
    public function getCoolLevelList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = $this -> getCoolLevel();
        return compact('code', 'msg', 'data');
    }


    /**
     * 用户炫酷值、炫酷等级
     *
     */
    public function getUserCoolInfo($userId)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {

            if ($userId<=0){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                throw new \Exception('参数错误-userId');
            }
            $modelUser = new User();
            $userInfo = $modelUser->get_user($userId);
            $data['user_info'] = $userInfo;
            $cool_val = $this->modelCoolval -> getUserCoolval($userId);
            $data['cool_val'] = $cool_val;

            $level_info = $this->modelCoolval -> getLevelByVal($cool_val);
            $next_level_info = [];
            if ($level_info){
                $level_info['icon_url'] = build_image($level_info['icon']);
                $level_info['icon_grey_url'] = build_image($level_info['icon_grey']);
                $level_info['content'] = json_decode($level_info['content'], true) ?? [];
                if ($level_info['content']){
                    $level_info['content']['per_minute'] = 3;
                }

                $whereInfo = ['level'=>$level_info['level'] +1];
                $next_level_info = $this->modelCoolval -> getCoolLevelInfo($whereInfo);
                if ($next_level_info){
                    $next_level_info['icon_url'] = build_image($next_level_info['icon']);
                    $next_level_info['icon_grey_url'] = build_image($next_level_info['icon_grey']);
                    $next_level_info['content'] = json_decode($next_level_info['content'], true) ?? [];
                    if ($next_level_info['content']){
                        $next_level_info['content']['per_minute'] = 3;
                    }
                }
            }

            $data['level_info'] = $level_info;
            $data['next_level_info'] = $next_level_info;

        } catch (\Exception $e) {
            $error = $e ->getMessage() . '-line:'.$e->getLine();
            write_log(
                'UserCoolvalServices'.(isCli()?'-cli':''),
                '[ERROR] getUserCoolInfo',
                ['error'=>$error, 'args'=>func_get_args()]
            );

        }

        return compact('code', 'msg', 'data');
    }


    /**
     * 实时队列添加-增加炫酷值
     *
     */
    public function taskUserCoolvalChange ($userId, $goodsId, $changeVal, $changeTyep=1, $changeDesc='增加炫酷值task') {

    }

    /**
     * 队列执行
     * @param $param
     * @return false
     */
    public function handUserCoolvalChange($param)
    {
        if (empty($param)){
            return false;
        }

        $uId = $param['user_id'] ?? 0;
        $gId= $param['goods_id'] ?? 0;
        $changeVal= $param['change_val'] ?? 0;
        $type = 1;//change_type
        $desc = $param['desc'] ?? '增加炫酷值';

        $service = new UserCoolvalServices();
        $res = $service -> userCoolvalChange($uId, $gId, $changeVal, $type, $desc);

        write_log(
            'UserCoolvalServices'.(isCli()?'-cli':''),
            '[INFO] 炫酷值变更-handIncUserCoolval',
            ['res'=>$res, 'args'=>func_get_args()]
        );

        $queueExecModel = new queueExecModel();
        if ($res && $res['code']==Hint::SUCCESS){
            $queueExecModel->updateRecordByCode(md5(json_encode($param)),1);
            return true;
        }else{
            $queueExecModel->updateRecordByCode(md5(json_encode($param)),2);
        }

        return false;
    }
    /**
     * 用户炫酷值增加
     * $changeTyep 1:增加
     *
     *
     * 炫酷值增加
        1、购买
        2、后台赠送
        3、道具开
        4、好友赠送
     *
     */

    public function userCoolvalChange($userId, $goodsId, $changeVal, $changeTyep=1, $changeDesc='增加炫酷值default')
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {
            if ($userId<=0){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                throw new \Exception('参数错误-userId');
            }
            if ($goodsId<=0){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                throw new \Exception('参数错误-goodsId');
            }
            if ($changeVal<=0){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                throw new \Exception('参数错误-changeVal');
            }
            if (!in_array($changeTyep, [1])){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                throw new \Exception('参数错误-changeType');
            }

            // 验证同sku商品是否累计过炫酷值
            $ifCool = $this->modelCoolval -> ifUserGoodsCool($userId, $goodsId);
            if ($ifCool){
                $msg = '无需增加';
                // return compact('code', 'msg', 'data');
                throw new \Exception('无需增加-UID:'.$userId.'-GID:'. $goodsId);
            }

            $UserCoolLevel = 1;
            $UserCoolval = $changeVal;
            $UserCoolInfo = $this->modelCoolval ->getUserCoolInfo($userId);
            if ($UserCoolInfo){
                $UserCoolLevel = $UserCoolInfo['cool_level']?:1;
                $UserCoolval = $UserCoolInfo['cool_val'] + $changeVal;
                $UserCoolval = $UserCoolval>0 ? $UserCoolval : 0;
            }
            // 计算等级
            $upgradeLevel = 1;
            $upgradeLevelInfo = $this->modelCoolval -> getLevelByVal($UserCoolval);
            if ($upgradeLevel){
                $upgradeLevel = $upgradeLevelInfo['level'] ?: 1;
            }

            $promoteLevel = [];
            for ($i=$UserCoolLevel; $i <= $upgradeLevel; $i++) {
                array_push($promoteLevel, $i);
            }

            DB::beginTransaction();
            $dataUcd = [];
            $dataUcd['user_id'] = $userId;
            $dataUcd['goods_id'] = $goodsId;
            $dataUcd['change_coolval'] = $changeVal;
            $dataUcd['change_type'] = $changeTyep;
            $dataUcd['change_desc'] = $changeDesc;
            $dataUcd['add_time'] = time();
            $resUcd = $this->modelCoolval ->addUserCoolDetails($dataUcd);
            if (!$resUcd){
                throw new \Exception('炫酷值记录插入失败');
            }
            if ($UserCoolInfo){
                $resUcv = $this->modelCoolval ->incUserCoolval($userId, $changeVal, $upgradeLevel);
            }else{
                $dataUcv = [];
                $dataUcv['user_id'] = $userId;
                $dataUcv['cool_val'] = $changeVal;
                $dataUcv['cool_level'] = $upgradeLevel;
                $dataUcv['edit_time'] = time();
                $resUcv = $this->modelCoolval ->addUserCoolval($dataUcv);
            }
            if (!$resUcv){
                throw new \Exception('炫酷值更新失败');
            }

            DB::commit();

            if ($promoteLevel){
                # 升级事件
                write_log(
                    'UserCoolvalServices'.(isCli()?'-cli':''),
                    '[INFO] 炫酷值变更升级-userCoolvalChange',
                    ['promoteLevel'=>$promoteLevel, 'args'=>func_get_args()]
                );
            }

        } catch (\Exception $e) {
            DB::rollBack();


            $error = $e ->getMessage() . '-line:'.$e->getLine();
            write_log(
                'UserCoolvalServices'.(isCli()?'-cli':''),
                '[ERROR] 炫酷值变更-userCoolvalChange',
                ['error'=>$error, 'args'=>func_get_args()]
            );
        }

        return compact('code', 'msg', 'data');
    }














}
